import { _decorator, Component, EventTouch, instantiate, Label, labelAssembler, Node, Prefab, Sprite, Tween, tween, UIOpacity } from 'cc';
import { PrefsManager } from '../AshFramework/Managers/PrefsManager';
import { PROPS, UITYPE, WEAPON, WEAPONSWITCH } from '../AshFramework/Datas/Constant';
import { ZTool } from '../AshFramework/Utils/ZTool';
import { BundleManager, Bundles } from '../AshFramework/Managers/BundleManager';
import { WeaponShow } from './WeaponShow';
import PlayerController from '../PlayerController';
import { NumberIncrementLabel } from './NumberIncrementLabel';
import { ResourceUtil } from '../AshFramework/Utils/ResourceUtil';
import { GameManager } from './GameManager';
import { HintController } from './HintController';
import { GameData } from './GameData';
import Banner from '../Banner';
import { AudioManager, Audios } from '../AshFramework/Managers/AudioManager';
import { EventManager, MyEvent } from '../AshFramework/Managers/EventManager';
const { ccclass, property } = _decorator;

@ccclass('UIManager')
export class TLWLSJ_UIManager extends Component {
    public static Instance: TLWLSJ_UIManager = null;

    @property(Node)
    Agonal: Node = null;

    @property(UIOpacity)
    AgonalUIOpacity: UIOpacity = null;

    @property(Node)
    Weapon: Node = null;

    @property(Node)
    Last: Node = null;

    @property(Node)
    Next: Node = null;

    @property(Sprite)
    HPSprite: Sprite = null;

    @property(Node)
    TipsNode: Node = null;

    @property(Node)
    TimeNode: Node = null;

    @property(Label)
    TimeLabel: Label = null;

    @property(UIOpacity)
    WaveUIOpacity: UIOpacity = null;

    @property(Label)
    WaveLabel: Label = null;

    @property(NumberIncrementLabel)
    YW: NumberIncrementLabel = null;

    @property(NumberIncrementLabel)
    KF: NumberIncrementLabel = null;

    @property(Node)
    DXPanel: Node = null;

    @property(Label)
    TipsLabel: Label = null;

    @property(Node)
    PackNode: Node = null;

    @property(Node)
    ShopNode: Node = null;

    @property(Node)
    CDZPanel: Node = null;

    IsAgonal: boolean = false;
    IsAgonalOnce: boolean = false;
    WeaponShowTs: WeaponShow = null;

    IsLock: boolean = false;

    private _cb: Function = null;

    protected onLoad(): void {
        TLWLSJ_UIManager.Instance = this;
        this.Last.on(Node.EventType.TOUCH_END, this.onLast, this);
        this.Next.on(Node.EventType.TOUCH_END, this.onNext, this);
    }

    protected start(): void {
        this.showWeapon();
        // this.showAgonalStaged();
        this.showYW();
        this.showKF();
    }

    showAgonalStaged() {
        if (this.IsAgonal) return;
        this.IsAgonal = true;
        this.Agonal.active = true;
        this.IsAgonalOnce = false;
        Tween.stopAllByTarget(this.AgonalUIOpacity);
        tween(this.AgonalUIOpacity)
            .to(0.5, { opacity: 100 }, { easing: `sineInOut` })
            .delay(0.5)
            .to(0.5, { opacity: 255 }, { easing: `sineInOut` })
            .delay(0.5)
            .union()
            .repeatForever()
            .start();
    }

    showAgonalStagedOnce() {
        if (this.IsAgonal || this.IsAgonalOnce) return;
        this.IsAgonalOnce = true;
        this.Agonal.active = true;
        tween(this.AgonalUIOpacity)
            .to(0.3, { opacity: 100 }, { easing: `sineInOut` })
            .call(() => {
                this.IsAgonalOnce = false;
                this.closeAgonalStaged();
            })
            .start();
    }

    closeAgonalStaged() {
        this.IsAgonal = false;
        this.Agonal.active = false;
        Tween.stopAllByTarget(this.AgonalUIOpacity);
    }

    onLast(event: EventTouch) {
        AudioManager.PlaySound(Audios.ButtonClick);
        this.showWeapon(WEAPONSWITCH.LAST);
        PrefsManager.Instance.saveData();
    }

    onNext(event: EventTouch) {
        AudioManager.PlaySound(Audios.ButtonClick);
        this.showWeapon(WEAPONSWITCH.NEXT);
        PrefsManager.Instance.saveData();
    }

    showWeapon(weapon: WEAPONSWITCH = WEAPONSWITCH.NON) {
        switch (weapon) {
            case WEAPONSWITCH.NON:
                break;
            case WEAPONSWITCH.LAST:
                PrefsManager.Instance.userData.CurWeapon = ZTool.getAdjacentElement(PrefsManager.Instance.userData.AllWeapon, PrefsManager.Instance.userData.CurWeapon, false);
                break;
            case WEAPONSWITCH.NEXT:
                PrefsManager.Instance.userData.CurWeapon = ZTool.getAdjacentElement(PrefsManager.Instance.userData.AllWeapon, PrefsManager.Instance.userData.CurWeapon);
                break;
        }

        this.Weapon.removeAllChildren();
        PlayerController.Instance.showWeapon();
        BundleManager.LoadPrefab(Bundles.Prefabs, `展示_武器_${ZTool.GetEnumKeyByValue(WEAPON, PrefsManager.Instance.userData.CurWeapon)}`).then((prefab: Prefab) => {
            const node: Node = instantiate(prefab);
            node.parent = this.Weapon;
            this.WeaponShowTs = node.getComponent(WeaponShow);
            this.IsLock = this.checkIsLock();
            if (this.IsLock) {
                BundleManager.LoadPrefab(Bundles.Prefabs, "Lock").then((prefab: Prefab) => {
                    const lock: Node = instantiate(prefab);
                    lock.parent = node;
                    //给锁注册点击事件
                    lock.on(Node.EventType.TOUCH_END, () => {
                        AudioManager.PlaySound(Audios.ButtonClick);
                        this.showDXPanel(UITYPE.武器, () => {
                            this.closeDXPanel();
                            PrefsManager.Instance.userData.HaveWeapon.push(PrefsManager.Instance.userData.CurWeapon);
                            GameData.addWeaponByType(PrefsManager.Instance.userData.CurWeapon);
                            this.showWeapon();
                        })
                    });
                })
            }
        })
    }

    getZDSQ() {
        GameData.addWeaponByType(WEAPON.自动手枪);
        PrefsManager.Instance.userData.HaveWeapon.push(WEAPON.自动手枪);
        PrefsManager.Instance.userData.CurWeapon = WEAPON.自动手枪;
        PrefsManager.Instance.saveData();
        this.Weapon.removeAllChildren();
        PlayerController.Instance.showWeapon();
        BundleManager.LoadPrefab(Bundles.Prefabs, `展示_武器_${ZTool.GetEnumKeyByValue(WEAPON, PrefsManager.Instance.userData.CurWeapon)}`).then((prefab: Prefab) => {
            const node: Node = instantiate(prefab);
            node.parent = this.Weapon;
            this.WeaponShowTs = node.getComponent(WeaponShow);
            this.IsLock = this.checkIsLock();
            this.scheduleOnce(() => { EventManager.Scene.emit(MyEvent.FL); }, 0.2);
        })
    }

    /**
     * 
     * @returns 检查当前装备是否被锁住 锁住返回true
     */
    checkIsLock() {
        if (PrefsManager.Instance.userData.HaveWeapon.findIndex(e => e == PrefsManager.Instance.userData.CurWeapon) == -1) {
            return true;
        }
        return false;
    }

    setHPFillRange(fillRange: number) {
        fillRange = ZTool.Clamp(fillRange, 0, 1);
        this.HPSprite.fillRange = fillRange;
    }

    time(time: number, wave: number, isLast: boolean = false, cb: Function = null) {
        this.TipsNode.active = true;
        this.TimeNode.active = true;
        this.startTime(time, wave, isLast, cb);
    }

    startTime(time: number = 0, wave: number, isLast: boolean = false, cb: Function = null) {
        if (time <= 0) {
            const tips = isLast ? `最后一波` : `第 ${wave} 波`;
            this.showTips(tips);
            cb && cb();
            return;
        }
        this.TimeLabel.string = time.toString();
        this.scheduleOnce(() => { this.startTime(time - 1, wave, isLast, cb) }, 1);
    }

    showTips(tips: string, cb: Function = null) {
        this.TipsNode.active = true;
        this.TimeNode.active = false;
        this.WaveUIOpacity.opacity = 255;
        this.WaveLabel.string = tips;
        tween(this.WaveUIOpacity)
            .delay(1)
            .to(2, { opacity: 0 }, { easing: `sineOut` })
            .call(() => { this.TipsNode.active = false; cb && cb() })
            .start();
    }

    showYW(change: number = 0) {
        PrefsManager.Instance.userData.YW += change;
        if (PrefsManager.Instance.userData.YW < 0) {
            PrefsManager.Instance.userData.YW = 0;
            this.showDXPanel(UITYPE.药物, () => {
                this.closeDXPanel();
                this.showYW(3);
                GameData.addPropByType(PROPS.药丸, 3);
            });
            return;
        }
        if (change < 0) {
            AudioManager.PlaySound(Audios.Drink);
            GameData.userPropByType(PROPS.药丸);
            PlayerController.Instance.propCure(PROPS.药丸);
        }
        PrefsManager.Instance.saveData();
        this.YW.playNumberIncrementTo(PrefsManager.Instance.userData.YW);
    }

    showKF(change: number = 0) {
        PrefsManager.Instance.userData.KF += change;
        if (PrefsManager.Instance.userData.KF < 0) {
            PrefsManager.Instance.userData.KF = 0;
            this.showDXPanel(UITYPE.药物, () => {
                this.closeDXPanel();
                this.showKF(1);
                GameData.addPropByType(PROPS.咖啡, 1);
            });
            return;
        }
        if (change < 0) {
            AudioManager.PlaySound(Audios.Drink);
            GameData.userPropByType(PROPS.咖啡);
            PlayerController.Instance.propCure(PROPS.咖啡);
        }
        PrefsManager.Instance.saveData();
        this.KF.playNumberIncrementTo(PrefsManager.Instance.userData.KF);
    }

    ShowTips(hint: string) {
        ResourceUtil.LoadPrefab("UI/Hint").then((prefab: Prefab) => {
            const node: Node = instantiate(prefab);
            node.parent = GameManager.Instance.Canvas;
            node.getComponent(HintController).showHint(hint);
        })
    }

    onButtonClick(event: EventTouch) {
        const target: Node = event.getCurrentTarget();
        switch (target.name) {
            case "药丸":
                if (PlayerController.Instance.isCure()) this.showYW(-1);
                else this.ShowTips("血量已满！")
                break;
            case "咖啡":
                if (PlayerController.Instance.isCure()) this.showKF(-1);
                else this.ShowTips("血量已满！")
                break;
        }
    }

    showDXPanel(type: UITYPE, cb: Function = null) {
        GameManager.Instance.IsPause = true;
        this.DXPanel.active = true;
        let tips = "";
        if (type == UITYPE.背包) {
            tips = "弹匣已用完！";
            this.PackNode.active = true;
            this.ShopNode.active = false;
        } else if (type == UITYPE.商店) {
            tips = "子弹已用完！";
            this.ShopNode.active = true;
            this.PackNode.active = false;
        } else if (type == UITYPE.武器) {
            tips = "武器未解锁！";
            this.ShopNode.active = true;
            this.PackNode.active = false;
        } else if (type == UITYPE.药物) {
            tips = "已用完！";
            this.ShopNode.active = true;
            this.PackNode.active = false;
        }
        this.TipsLabel.string = tips;
        this._cb = cb;
    }

    closeDXPanel() {
        GameManager.Instance.IsPause = false;
        this.DXPanel.active = false;
        this._cb = null;
    }

    playViedo() {
        AudioManager.PlaySound(Audios.ButtonClick);
        Banner.Instance.ShowVideoAd(() => { this._cb && this._cb() });
    }

    openPack() {
        this.closeDXPanel();
        GameManager.Instance.backpackBtn();
    }

    openShop() {
        this.closeDXPanel();
        GameManager.Instance.shopBtn();
    }

    showCDZPanel(cb: Function = null) {
        GameManager.Instance.IsPause = true;
        this.CDZPanel.active = true;
        this._cb = cb;
    }

    closeCDZPanel() {
        GameManager.Instance.IsPause = false;
        this.CDZPanel.active = false;
        this._cb = null;
    }

    // updateWeapon() {
    //     if (this.WeaponShowTs.Type == WEAPONSHOW.NON) {
    //         return;
    //     }

    //     const magazine: Magazine = (PlayerController.Instance.WeaponTs as Gun).CurMagazine;
    //     let num: number = 0;
    //     if (magazine) {
    //         num = magazine.Bullets.length;
    //     }
    //     if (this.WeaponShowTs.Type == WEAPONSHOW.FILL) {
    //         this.WeaponShowTs.showBulletNum(num);
    //     } else if (this.WeaponShowTs.Type == WEAPONSHOW.INSTANT) {
    //         this.WeaponShowTs.showBulletNum(num);
    //         const bullets = GameData.getBulletByWeapon(PrefsManager.Instance.userData.CurWeapon);
    //         if (bullets.length > 0) {
    //             this.WeaponShowTs.showBullet(bullets[0].Name);
    //         } else {
    //             this.WeaponShowTs.showBullet();
    //         }
    //     }
    // }
}


